﻿using System;
using System.Collections.Generic;
using System.Text;
using TCCHWLib.Commands;
using System.Windows.Forms;

namespace TCCCompiler
{
   public class Expression:IExpression
    {
        List<IExpression> Parts = new List<IExpression>();
        TreeNode Currennt_Node;

        List<string> operators = new List<string>();
        private void Get_Expression()
        {
            for (int i = 0; i < Currennt_Node.Nodes.Count; i++)
            {
                switch (Currennt_Node.Nodes[i].Text)
                {
                    case "EXP":
                        Expression exp = new Expression(Currennt_Node.Nodes[i]);
                        exp.Get_Expression();
                        Parts.Add(exp);
                        break;

                    case "TERM":
                        Term term = new Term(Currennt_Node.Nodes[i]);
                        Parts.Add(term);
                        break;

                    case "Operator":
                        operators.Add(Currennt_Node.Nodes[i].Nodes[0].Text.Trim());
                        break;
                }
            }
        }
       public void evaluate_Exp()
       {
           this.Commands.AddRange(Parts[0].Commands);
           object parameter_1 = Parts[0].Value;
           Parts.RemoveAt(0);
           object parameter_2;

           for (int i = 0; i < Parts.Count; i++)
           {
               parameter_2 = Parts[i].Value;
               this.Commands.AddRange(Parts[i].m_Commands);
               switch (operators[i].Trim())
               {
                   case "+":
                       AddCommand ADD = new AddCommand(parameter_1, parameter_2, operators[i]);
                       this.Commands.Add(ADD);
                       parameter_1 = this.Commands[i].Value;
                       break;
                   case "-":
                       SubCommand SUB = new SubCommand(parameter_1, parameter_2, operators[i]);
                       this.Commands.Add(SUB);
                       parameter_1 = this.Commands[i].Value;
                       break;
                   case "/":
                       DivCommand DIV = new DivCommand(parameter_1, parameter_2, operators[i]);
                       this.Commands.Add(DIV);
                       parameter_1 = this.Commands[i].Value;
                       break;
                   case "*":
                       MulCommand MUL = new MulCommand(parameter_1, parameter_2, operators[i]);
                       this.Commands.Add(MUL);
                       parameter_1 = this.Commands[i].Value;
                       break;
               }
           }
       }
       public Expression(TreeNode Node)
        {
            Currennt_Node = Node;
            Get_Expression();
            evaluate_Exp();
            
        }
    }
}

